<template>
  <div style="width: auto; height: 270px" id="echarts1"></div>
</template>
<script>
import * as echarts from "echarts";
const colors = ["#5470C6", "#EE6666"];
import { listEcharts1 } from "@/api/echarts/echarts";
export default {
  name: "echarts1",
  data() {
    return {
      // option配置
      option: {
        title: {
          text: "模型涉及部门分布",
          subtext: "",
          left: "center",
          textStyle: {
            color: "#FFFFFF",
          },
        },
        tooltip: {
          trigger: "item",
        },
        legend: {
          orient: "vertical",
          left: "left",
          textStyle: {
            color: "#FFFFFF",
          },
        },
        series: [
          {
            name: "部门",
            type: "pie",
            radius: "50%",
            data: [],
            center: ["60%", "60%"], // 将图表向右边移动
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)",
              },
            },
            label: {
              show: true,
              position: "outside",
              // formatter: "{b}: {c} ({d}%)",
              textStyle: {
                color: "#FFFFFF",
              },
            },
          },
        ],
      },
      loading: false,
      categories: [],
      total: 0,
    };
  },
  mounted() {
    this.getList();
  },
  methods: {
    echartsInit() {
      // 确保 DOM 元素已加载
      this.$nextTick(() => {
        const chart = echarts.init(document.getElementById("echarts1"));
        chart.setOption(this.option);

        // 添加点击事件监听器
        chart.on("click", (params) => {
          if (params.seriesType === "pie") {
            const type = params.name;
            this.goToCategoryPage(type);
          }
        });
      });
    },

    getList() {
      this.loading = true;
      listEcharts1()
        .then((response) => {
          this.categories = response.rows.filter(
            (item) => item.type !== "总数"
          );
          this.total = response.rows.find((item) => item.type === "总数").count;

          // 转换数据格式
          this.option.series[0].data = this.categories.map((item) => ({
            value: item.count,
            name: item.type,
          }));

          // 重新初始化图表
          this.echartsInit();

          this.loading = false;
        })
        .catch((error) => {
          console.error("Error fetching data:", error);
          this.loading = false;
        });
    },

    goToCategoryPage(type) {
      // 跳转到指定页面并传递参数
      this.$router.push({ path: "../model/model", query: { type: type } });
    },
  },
};
</script>

<style scoped>
/* 你可以在这里添加样式 */
</style>
